#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "wifi_device.h"
#include "lwip/opt.h"
#include "lwip/api.h"
#include "lwip/dhcp.h"
#include "lwip/netifapi.h"
#include "lwip/api_shell.h"

// err_t static_ip_assigned(struct netif *netif) {
//     ip_addr_t ipaddr;
//     ip_addr_t netmask;
//     ip_addr_t gw;
 
//     // 设置静态 IP 地址
//     IP4_ADDR(&ipaddr, 192, 168, 1, 10); // 例: 192.168.1.10
//     IP4_ADDR(&netmask, 255, 255, 255, 0); // 子网掩码: 255.255.255.0
//     IP4_ADDR(&gw, 192, 168, 1, 1); // 默认网关: 192.168.1.1
 
//     // 调用 netifapi 来设置 IP 地址
//     // netifapi_netif_common(netif, &ipaddr, &netmask,&gw);
//     // netifapi_netif_set_addr_hint(netif,&ipaddr,&netmask,&gw);
//     // netifapi_netif_set_up(netif);
//     return ERR_OK;
// }

void connect_wifi(void){
    WifiErrorCode errCode;
    WifiDeviceConfig apConfig = {};
    int netId = -1;

    strcpy(apConfig.ssid, "H9");
    strcpy(apConfig.preSharedKey,"13387731118");
    apConfig.securityType = WIFI_SEC_TYPE_PSK;

    errCode = EnableWifi();
    errCode = AddDeviceConfig(&apConfig,&netId);

    // errCode = EnableWifi();
    // errCode = AddDeviceConfig(&apConfig,&netId);

    errCode = ConnectTo(netId);
    printf("Connected %d: %d\r\n",netId,errCode);
    usleep(1000*1000);

    struct netif *iface = netifapi_netif_find("wlan0");
    if (iface)
    {
        err_t ret = netifapi_dhcp_start(iface);
        sleep(1);
        netifapi_dhcp_release(iface);
        sleep(1);
        ret = netifapi_dhcp_start(iface);
        printf("netifapi_dhcp_start:%d\r\n",ret);

        // static_ip_assigned(iface);
        sleep(5);
        ret = netifapi_netif_common(iface,dhcp_clients_info_show,NULL);
        printf("netfapi_netif_common:%d\r\n",ret);
    }
    
}

